<?php

/*
*首页接口类
*/

namespace interface\v1;

class homeStoreClass extends index
{
	private const tableOrder       = 'store_order';
	private const tableOrderDetail = 'store_order_detail';
	private const tableTarget      = 'store_product';
	private static string $cid  = 'ab3c4d8d235c26ff';
	private static string $khid = 'aff27e1a45c3ab73';
	
	
	/**
	 * 获取排序规则
	 *
	 * @return void
	 */
	public function getType()
	{
		$this->code         = 1;
		$this->resp['data'] = [
			[
				'text' => '默认',
				'key'  => 'default',
			],
			[
				'text' => '新品',
				'key'  => 'new',
			],
			[
				'text' => '销量',
				'key'  => 'sales',
			],
			[
				'text' => '价格',
				'key'  => 'price',
			],
		];
	}
	
	/**
	 * 商品分类
	 *
	 * @param $where
	 * @return array
	 */
	public static function goodsType($where = '')
	{
		$where     = $where ?: ' pid = \'0\' ';
		$thumbnail = root . 'img/miniProgram/store/thumb.png';
		$result    = find([
			'table' => 'material_type',
			'where' => $where . " and coid = '" . self::$coid . "' order by list asc",
			'field' => " id as groupId, name, '$thumbnail' as `thumbnail`  ",
		]);
		$items     = [];
		foreach ($result['array'] as $key => $item) {
			$items[$key] = $item;
			$has         = query('material_type', " pid = '{$item['groupId']}'  ");
			if ($has['id']) {
				$items[$key]['children'] = self::goodsType(" pid = '{$item['groupId']}' ");
			} else {
				$items[$key]['children'][0] = $item;
			}
		}
		return $items;
	}
	
	/**
	 * 获取商品分类
	 *
	 * @return void
	 */
	public function getGoodsType()
	{
		$this->code         = 1;
		$this->resp['data'] = static::goodsType();
	}
	
	// 获取商品列表
	public function getGoods()
	{
		$this->code = 1;
		$where      = '';
		(int)$page = (is_numeric($this->get('p'))) ? abs($this->get('p')) : 1;    //页码
		(int)$num = (is_numeric($this->get('num'))) ? abs($this->get('num')) : 6; //条数
		$page  = $page > 0 ? $page : 1;
		$start = ($page - 1) * $num;                                              //起始位置
		$limit = "  LIMIT $start,$num ";
		$sql   = "SELECT `id` as spuId, `materialId`, `materialSkuId`, `price`, `isNew`, `sales`, `text`, `state` FROM `" . self::tableTarget . "` WHERE 1=1 AND state = '上架' ";
		$order = ' ORDER BY `time` DESC'; //排序
		// 从首页过来
		switch ($this->post('act')) {
			case 'new':
				$sql = str_replace('1=1', " 1=1 AND isNew = '是' ", $sql);
				break;
			case 'price':
				$order = ' ORDER BY `price` DESC ';
				break;
			case 'sales':
				$order = ' ORDER BY `sales` DESC ';
				break;
			default:
				break;
		}
		// 分类
		if ($this->post('pid')) {
			$sql = str_replace('1=1', " 1=1 AND typeId = '{$this->post('pid')}' ", $sql);
		}
		// 关键字
		if ($this->post('keyword')) {
			$sql = str_replace('1=1', " 1=1 AND materialId IN (SELECT id FROM `material` WHERE name LIKE '%{$this->post('keyword')}%' ) ", $sql);
		}
		$sql = $sql . $where . $order . $limit;
		$res = sqlFind($sql);
		foreach ($res as $key => $item) {
			$material                 = query('material', " id = '$item[materialId]' ");
			$res[$key]['title']       = $material['name'] . $material['code'] . $material['model'];
			$res[$key]['originPrice'] = 0;
			$res[$key]['thumb']       = root . 'img/miniProgram/store/thumb.png';
		}
		if (!$res) {
			$this->resp['warn'] = '暂无结果';
		} else {
			$this->resp = [
				'data' => $res,
			];
		}
	}
	
	// 获取收藏商品列表
	public function getCollectGoods()
	{
		$this->code = 1;
		$where      = '';
		(int)$page = (is_numeric($this->get('p'))) ? abs($this->get('p')) : 1;    //页码
		(int)$num = (is_numeric($this->get('num'))) ? abs($this->get('num')) : 6; //条数
		$page  = $page > 0 ? $page : 1;
		$start = ($page - 1) * $num;                                              //起始位置
		$limit = "  LIMIT $start,$num ";
		$sql   = "SELECT `spid` FROM `store_collect` WHERE ctid = '" . self::$cid . "' ";
		$order = ' ORDER BY `time` DESC'; //排序
		$sql   = $sql . $where . $order . $limit;
		$res   = sqlFind($sql);
		$items = [];
		foreach ($res as $key => $item) {
			$info = query('store_product', " id = '$item[spid]' ");
			if (!$info['id']) {
				continue;
			}
			$material         = query('material', " id = '$info[materialId]' ");
			$storeClient      = query('store_client', " id = '" . self::$cid . "' ", 'khid');
			$storeClientPrice = query('store_client_price', " khid = '$storeClient[khid]' AND  materialSkuId = '{$info['materialSkuId']}'  ");
			$items[]          = [
				'spuId'     => $item['spid'],
				'title'     => $material['name'] . $material['code'] . $material['model'],
				'thumb'     => root . 'img/miniProgram/store/thumb.png',
				'price'     => (string)($storeClientPrice['price'] ?: $info['price']),
				'collected' => 1,
				'addCart'   => 0,
			];
		}
		if (!$res) {
			$this->resp['warn'] = '暂无结果';
		} else {
			$this->resp = [
				'data' => $items,
			];
		}
	}
	
	/**
	 * 处理收藏
	 *
	 * @return void
	 */
	public function actCollectGoods()
	{
		$id    = $this->post('id');
		$act   = $this->post('act') ?? 'add';
		$goods = query(self::tableTarget, " id = '$id' ");
		if (self::isNull($goods['id'])) {
			$this->resp['warn'] = '参数错误';
		} else {
			$where        = " spid = '$id' and ctid = '" . self::$cid . "' ";
			$storeCollect = query('store_collect', $where);
			if ($act === 'add') {
				$type = '商品收藏';
				if (!self::isNull($storeCollect['id'])) {
					$warn = '该商品已收藏';
				} else {
					$warn = static::insert([
						'table' => 'store_collect',
						'field' => [
							'id'   => self::getNo(),
							'coid' => self::$coid,
							'spid' => $id,
							'ctid' => self::$cid,
						],
					]);
				}
			} else {
				$type = '收藏商品取消';
				if (!$storeCollect['id']) {
					$warn = '还未收藏该商品';
				} else {
					$warn = delete([
						'table' => 'store_collect',
						'where' => $where,
					]);
				}
			}
			if (!in_array($warn, ['新增成功', '更新成功', '删除成功'])) {
				$this->resp['warn'] = '处理失败，' . $warn;
			} else {
				$this->code         = 1;
				$this->resp['warn'] = $type . '成功';
			}
		}
	}
	
	// 获取商品详情
	public function getDetails()
	{
		$id   = $this->get('id') ?? '';
		$info = query(self::tableTarget, " id = '$id' ", " `id`, `materialId`, `materialSkuId`, `price`, `isNew`, `sales`  ");
		if (empty($id) || empty($info['id'])) {
			$this->resp['warn'] = '参数错误';
		} else {
			$material           = query('material', " id = '{$info['materialId']}' ", "`typeId`, `barcode`, `code`, `name`, `brand`, `model`, `unit`, `unit_one`, `unit_two` ");
			$materialSku        = query('material_sku', " id = '{$info['materialSkuId']}' ", 'id, name');
			$khid               = 'a1f4df4e83ab9dd1';
			$storeClientPrice   = query('store_client_price', " khid = '$khid' AND  materialSkuId = '{$info['materialSkuId']}'  ");
			$defaultImg         = root . 'img/miniProgram/store/thumb.png';
			$storeCollect       = query('store_collect', " spid = '{$info['id']}' AND ctid = '" . self::$cid . "'  ", 'id');
			$this->resp['data'] = [
				'spuId'            => $info['id'],
				'collected'        => $storeCollect['id'] ? 1 : 0,
				'title'            => $material['name'] . $material['code'] . $material['model'] . $materialSku['name'],
				'primaryImage'     => $defaultImg,
				'available'        => 1,
				'spuStockQuantity' => 50,// 库存
				'minSalePrice'     => $storeClientPrice['dealPrice'] ?: $info['price'],
				'maxLinePrice'     => $storeClientPrice['dealPrice'] ?: $info['price'],
				'skuList'          => [
					[
						'skuId'     => $materialSku['id'],
						'skuImage'  => $defaultImg,
						'specInfo'  => [
							[
								'specId'      => 10012,
								'specTitle'   => null,
								'specValueId' => 10012,
								'specValue'   => null,
							],
							[
								'specId'      => 10013,
								'specTitle'   => null,
								'specValueId' => 10013,
								'specValue'   => null,
							],
							[
								'specId'      => 10013,
								'specTitle'   => null,
								'specValueId' => 10014,
								'specValue'   => null,
							],
						],
						'stockInfo' => [
							'stockQuantity'     => 175,
							'safeStockQuantity' => 0,
							'soldQuantity'      => 0,
						],
					],
				],
				'specList'         => [
					[
						'specId'        => 10011,
						'title'         => '颜色',
						'specValueList' => [
							[
								'specValueId' => 10012,
								'specValue'   => '米色荷叶边',
							],
						],
					],
					[
						'specId'        => 10012,
						'title'         => '尺寸',
						'specValueList' => [
							[
								'specValueId' => 10012,
								'specValue'   => 'S',
							],
							[
								'specValueId' => 10013,
								'specValue'   => 'M',
							],
							[
								'specValueId' => 10014,
								'specValue'   => 'L',
							],
						],
					],
				],
				'images'           => [
					$defaultImg,
					$defaultImg,
					$defaultImg,
				],
			];
			
			$this->code = 1;
		}
	}
	
	/**
	 * 加入购物车
	 *
	 * @return void
	 */
	public function addGoods()
	{
		$id    = $this->post('id');
		$num   = $this->post('num') ?: 0;
		$goods = query(self::tableTarget, " id = '$id' ");
		if (self::isNull($goods['id'])) {
			$this->resp['warn'] = '参数错误';
		} else {
			$info        = query(self::tableTarget, " id = '$id' ");
			$client      = query('store_client', " id = '" . self::$cid . "' ");
			$material    = query('material', " id = '{$info['materialId']} '");
			$clientPrice = query('store_client_price', " khid = '" . self::$khid . "' AN materialSkuId = '" . $info['materialSkuId'] . "' ", 'dealPrice');
			$price       = $clientPrice['agreedPrice'] ?? $info['price'];
			$rate        = $clientPrice['dealPrice'] ?? $material['saleRate'];
			// 修改条件
			$where = generateWhere([
				'coid'    => self::$coid,
				'ctid'    => self::$cid,
				'orderId' => 1,
				'spid'    => $info['id'],
			]);
			$res   = query('store_order_detail', $where);
			if ($res['id']) {
				$bool = static::update([
					'table' => self::tableOrderDetail,
					'field' => [
						'num'   => ($num > 0) ? $num : (abs($res['num']) + 1),
						'money' => ($num > 0) ? $num * (1 + $res['rate']) : (abs($res['num']) + 1) * (1 + $res['rate']),
					],
					'where' => $where,
				]);
			} else {
				$bool = static::insert([
					'table' => self::tableOrderDetail,
					'field' => [
						'id'            => self::getNo(),
						'coid'          => self::$coid,
						'ctid'          => self::$cid,
						'orderId'       => '1',
						'spid'          => $info['id'],
						'materialId'    => $info['materialId'],
						'materialSkuId' => $info['materialSkuId'],
						'orderNum'      => 1,
						'num'           => 1,
						'unit'          => $material['unit'],
						'price'         => $price,
						'rate'          => $rate,
						'money'         => $price * (1 + $rate),
					],
				]);
			}
			
			if (!in_array($bool, ['新增成功', '更新成功'])) {
				$this->resp['warn'] = '加入购物车失败，未知错误';
			} else {
				$this->code         = 1;
				$this->resp['warn'] = '处理成功';
			}
		}
	}
	
	
	/**
	 * 获取购物车
	 *
	 * @return void
	 */
	public function getCart()
	{
		$this->code = 1;
		$where      = generateWhere([
			'coid'    => self::$coid,
			'ctid'    => self::$cid,
			'orderId' => 1,
		]);
		$result     = find([
			'table' => 'store_order_detail',
			'field' => ' spid as spuId, materialId, materialSkuId as skuId, price, num as quantity',
			'where' => $where,
		]);
		$items      = [];
		$thumb      = root . 'img/miniProgram/store/thumb.png';
		foreach ($result['array'] as $item) {
			$material    = query('material', " id = '$item[materialId]' ");
			$materialSku = query('material_sku', " id = '$item[skuId]' ", 'name');
			$items[]     = array_merge($item, [
				'thumb'         => $thumb,
				'primaryImage'  => $thumb,
				'title'         => $material['name'] . $material['code'] . $material['model'],
				'specs'         => $materialSku['name'],
				// 'stockQuantity' => inventoryBalanceClass::inventoryNum($item['skuId']),
				'stockQuantity' => 10,
				'isSelected'    => 0,
			]);
		}
		$totalAmount        = find([
			'table' => 'store_order_detail',
			'sum'   => 'money',
			'where' => $where,
		]);
		$this->resp['data'] = [
			'isNotEmpty'          => (count($items) > 0),
			'cartGoods'           => $items,
			'isAllSelected'       => false,
			'goodsCount'          => count($items),
			'totalAmount'         => $totalAmount > 0 ? $totalAmount * 100 : $totalAmount,
			'totalDiscountAmount' => 0,
		];
	}
	
}
